/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package org.karol.lx.agent;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import org.karol.lx.model.GradeRequest;

/**
 *
 * @author karol
 */
public class GraderAgent /*extends UnicastRemoteObject*/ implements IGraderAgent, GraderEventListener {
    
    //private ArrayList<Grader> mGraders = new ArrayList<>();
    private int mTotalGrader;
    private int mUsedGrader = 0;
    private ArrayList<GradeRequest> mHandledRequest = new ArrayList<>();

    public GraderAgent(int graderNum) {
        mTotalGrader = graderNum;
        
//        for (int i = 0 ; i < graderNum ; i++) {
//            try {
//                mGraders.add(new Grader(InetAddress.getLocalHost().getHostAddress() + "-" + i));
//            } catch (UnknownHostException ex) {
//                Logger.getLogger(StandardGraderAgent.class.getName()).log(Level.SEVERE, null, ex);
//            }
//        }
    }

    @Override
    public int getTotalGrader() {
//        return mGraders.size();
        return mTotalGrader;
    }

    @Override
    public ArrayList<Integer> getServedAction() {
        ArrayList<Integer> retval = new ArrayList<>();
        
        //TODO: fix this
        retval.add(0);
        retval.add(1);
        
        return retval;
    }

    @Override
    public int getAvailableGrader() {
//        int retval = 0;
//        for (Grader g : mGraders) {
//            if (g.getStatus() == Grader.STATUS_IDLE)
//                retval++;
//        }
//        return retval;
        return mTotalGrader - mUsedGrader;
    }

    @Override
    public synchronized boolean offerRequest(GradeRequest pRequest) throws GraderAgentException {
//        for (Grader g : mGraders) {
//            if (g.getStatus() == Grader.STATUS_IDLE) {
//                g.grade(pRequest);
//                break; //TODO: fix this
//            }
//        }
        pRequest.m_DispatchTime = new Date(Calendar.getInstance().getTimeInMillis());
        mHandledRequest.add(pRequest);
        (new Thread(new GraderBackgroundWorker(this , pRequest))).start();
        
        ///TODO: implement using HttpRequest, do it async when taking response
        
        return true;
    }

    @Override
    public boolean isRequestAcceptable(GradeRequest pRequest) {
        //TODO: implement this
        return true;
    }

    @Override
    public ArrayList<GradeRequest> getHandledRequest() {
        return mHandledRequest;
    }

    @Override
    public void onGradingSuccess(GradeRequest pRequest) {
        System.out.println(pRequest + " success");
    }

    @Override
    public void onGradingFailed(GradeRequest pRequest, Object pReason) {
        System.out.println(pRequest + " failed because " + pReason);
    }
    
}
